package com.ruoyi.web.controller.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.web.controller.TiebaForums.domain.TiebaForums;
import com.ruoyi.web.controller.TiebaForums.mapper.TiebaForumsMapper;
import com.ruoyi.web.controller.TiebaPostCollectGuanzhu.domain.TiebaPostCollectGuanzhu;
import com.ruoyi.web.controller.TiebaPostCollectGuanzhu.mapper.TiebaPostCollectGuanzhuMapper;
import com.ruoyi.web.controller.TiebaPosts.domain.TiebaPosts;
import com.ruoyi.web.controller.TiebaPosts.mapper.TiebaPostsMapper;
import com.ruoyi.web.controller.tiebauser.domain.TiebaUsers;
import com.ruoyi.web.controller.tiebauser.service.ITiebaUsersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMenuService;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Api(tags = "用户登录接口")
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Resource
    private ITiebaUsersService tiebaUsersService;

    @Resource
    private TiebaForumsMapper tiebaForumsMapper;

    @Resource
    private TiebaPostsMapper tiebaPostsMapper;

    @Resource
    private TiebaPostCollectGuanzhuMapper guanzhuMapper;


    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    @ApiOperation("用户-登录接口")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        // loginBody.getCode(), loginBody.getUuid()
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword());

        //

        // 同步注册用户信息
//        TiebaUsers tiebaUsers = new TiebaUsers();
//        tiebaUsers.setUsername(loginBody.getUsername());
//        tiebaUsers.setPassword(loginBody.getPassword());
//        tiebaUsersService.save(tiebaUsers);

        // 构造请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("password", loginBody.getPassword());
        requestBody.put("username", loginBody.getUsername());
        String url = "http://localhost:8080/tiebauser/tiebauser";
        // 调用外部接口
        try {
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(token); // 设置 Bearer Token
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
            ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);
            // 打印响应结果（可选）
            System.out.println("同步用户信息到外部接口成功，响应内容：" + response.getBody());
        } catch (Exception e) {
            System.err.println("同步用户信息到外部接口失败：" + e.getMessage());
        }


        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 获取当前用户的发帖数量
        int postCount = Math.toIntExact(tiebaPostsMapper.selectCount(new QueryWrapper<TiebaPosts>().eq("user_id", user.getUserId())));
        // 获取当前用户的贴吧数量
        int forumCount = Math.toIntExact(tiebaForumsMapper.selectCount(new QueryWrapper<TiebaForums>().eq("user_id", user.getUserId())));
        // 获取当前用户关注的数量
        int guanzhuCount = Math.toIntExact(guanzhuMapper.selectCount(new QueryWrapper<TiebaPostCollectGuanzhu>().eq("user_id", user.getUserId())));
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        ajax.put("postCount", postCount); // 添加发帖数量
        ajax.put("forumCount", forumCount); // 添加贴吧数量
        ajax.put("guanzhuCount", guanzhuCount); // 添加贴吧数量
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
